import React, { useMemo, useState } from 'react'
import { useHistory } from 'react-router-dom'
import {
  Input,
  Stack,
  InputGroup,
  InputLeftAddon,
  FormHelperText,
  Button,
  FormControl,
  Checkbox,
  FormLabel,
  Flex,
  Link, Text
} from '@chakra-ui/core'
import { FaLock } from 'react-icons/fa'
import { AiFillMail } from 'react-icons/ai'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import SocialWay from '../SocialWay'
import { signIn } from '../../apis/sign'

const bgColor = 'hsla(0,0%,71%,.1)'
const textColor = '#999'

function SignIn () {
  const [checked, setChecked] = useState(true)
  const [error, setError] = useState({})
  const errorArr = useMemo(() => Object.entries(error), [error])
  const history = useHistory()
  const handleChange = () => setChecked(!checked)

  const formik = useFormik({
    initialValues: {
      email: window.localStorage.getItem('email') || '',
      password: ''
    },
    validationSchema: Yup.object({
      email: Yup.string()
        .email('请输入正确邮箱格式')
        .required('请输入邮箱'),
      password: Yup.string()
        .min(6, '密码长度不能小于6')
        .required('请输入密码')
    }),
    onSubmit: async user => {
      try {
        await signIn({ user })
        if (checked) {
          window.localStorage.setItem('email', user.email)
        } else {
          window.localStorage.removeItem('email')
        }
        // 跳转首页
        history.push('/home')
      } catch (e) {
        setError(e.response.data.errors)
      }
    }
  })

  return (
    <form onSubmit={formik.handleSubmit}>
      <Stack>
        <FormControl isInvalid={!!(formik.touched.email && formik.errors.email)}>
          <InputGroup>
            <InputLeftAddon children={<AiFillMail />} bgColor={bgColor} />
            <Input name="email" placeholder="请输入邮箱" bgColor={bgColor} {...formik.getFieldProps('email')} />
          </InputGroup>
          {
            formik.touched.email && formik.errors.email ? <FormHelperText color="#e53e3e">{formik.errors.email}</FormHelperText> : null
          }
        </FormControl>
        <FormControl isInvalid={!!(formik.touched.password && formik.errors.password)}>
          <InputGroup>
            <InputLeftAddon children={<FaLock />} bgColor={bgColor} />
            <Input name="password" type="password" placeholder="请输入密码" bgColor={bgColor} {...formik.getFieldProps('password')} />
          </InputGroup>
          {
            formik.touched.password && formik.errors.password ? <FormHelperText color="#e53e3e">{formik.errors.password}</FormHelperText> : null
          }
        </FormControl>
        <Flex w="100%" align="center" justify="space-between" py={3}>
          <Flex align="center">
            <Checkbox isChecked={checked} onChange={handleChange} value="1" id="rememberMe" />
            <FormLabel htmlFor="rememberMe" m={0} ml={2} color={textColor}>记住我</FormLabel>
          </Flex>
          <Link fontSize="sm" color={textColor} _hover={{ textDecoration: 'none', color: '#333' }}>登录遇到问题?</Link>
        </Flex>
        <Button type="submit" colorScheme="teal" bgColor="#3194d0" w="100%" borderRadius="full" _hover={{ bgColor: '#187cb7' }}>登录</Button>
        {
          errorArr.map((item, i) => <Text color="#e53e3e" key={i + item[0]}>{item.join(' ')}</Text>)
        }
        <SocialWay type="登录" />
      </Stack>
    </form>
  )
}

export default SignIn